import 'package:base/base/theme.dart';
import 'package:base/base_lib.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:search/res/images.dart';
import 'package:search/res/lang.dart';

class PullZoomImgView extends StatefulWidget {
  Widget Function(BuildContext context, int index) builder;

  PullZoomImgView({Key? key, required this.builder}) : super(key: key);

  @override
  _PullZoomImgViewState createState() => _PullZoomImgViewState();
}

class _PullZoomImgViewState extends State<PullZoomImgView>
    with TickerProviderStateMixin {
  double expandedHeight = 300.h;
  double offsetY = 0;
  var top = 0.0;
  var opacity = 0.0;

  ScrollController controller = ScrollController(initialScrollOffset: 0);

  ValueNotifier<double> scrollDy = ValueNotifier<double>(0);
  ValueNotifier<double> searchBarNotify = ValueNotifier<double>(0);

  @override
  void initState() {
    controller.addListener(() {
      offsetY = controller.offset;
      if (offsetY <= 0) {
        scrollDy.value = offsetY;
      } else {
        searchBarNotify.value = offsetY;
      }
      print("offsetY${offsetY}");
    });
    super.initState();
  }

  _resetWithAnimation(bool delay) {
    if (controller.hasClients && offsetY < 0) {
      controller.animateTo(scrollDy.value,
          duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Listener(
        onPointerDown: (e) {
          print("onPointerDown${e.position.distance}===${e.position.dy}");
        },
        onPointerUp: (e) {
          _resetWithAnimation(false);
        },
        child: Stack(children: [
          ValueListenableBuilder<double>(
            valueListenable: scrollDy,
            builder: (BuildContext context, value, Widget? child) {
              return BgImageView(value: value, expandedHeight: expandedHeight);
            },
          ),
          CustomScrollView(
            clipBehavior: Clip.none,
            controller: controller,
            physics: const BouncingScrollPhysics(),
            slivers: <Widget>[
              SliverAppBar(
                // Provide a standard title.
                title: ValueListenableBuilder<double>(
                    valueListenable: searchBarNotify,
                    builder: (BuildContext context, value, Widget? child) {
                      print("LayoutBuilder:$value----$opacity");
                      return GestureDetector(
                          onDoubleTap: () {},
                          child: Container(
                            width: double.infinity,
                            height: 40.h,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(20),
                                color: opacity > 0.6
                                    ? KColors.c_D8D8D8
                                    : Colors.white),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SearchImageRes.ic_search.assetImage(
                                    width: 26.w, color: KColors.primaryColor),
                                SizedBox(width: 10.w),
                                Text(SearchStrRes.search_bar_hint)
                              ],
                            ),
                            // Provide a flexible space so that SliverAppBar can expand and
                            // contract along with the scroll position.
                          ));
                    }),
                centerTitle: true,
                // Allows the user to reveal the app bar if they begin scrolling
                // back up the list of items.
                floating: false,
                pinned: true,
                backgroundColor: Colors.transparent,
                // Display a placeholder widget to visualize the shrinking size.
                flexibleSpace: LayoutBuilder(
                  builder: (context, constraints) {
                    var appbarHeight =
                        MediaQuery.of(context).padding.top + kToolbarHeight;
                    top = constraints.biggest.height;
                    final scale = (expandedHeight - top) /
                        (expandedHeight - appbarHeight);
                    opacity = double.tryParse(scale.toStringAsFixed(1)) ?? 0;
                    if (opacity < 0) {
                      opacity = 0;
                    } else if (opacity > 1) {
                      opacity = 1;
                    }
                    print("top:${top}---${appbarHeight}---${opacity}");
                    return Opacity(
                      opacity: opacity,
                      child: Container(
                        color: Colors.white,
                      ),
                    );
                  },
                ),
                // Make the initial height of the SliverAppBar larger than normal.
                expandedHeight: 350.h,
              ),
              SliverList(delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return widget.builder(context, index);
                },
              )),
            ],
          )
        ]));
  }
}

class BgImageView extends StatelessWidget {
  final double value, expandedHeight;

  const BgImageView({
    Key? key,
    required this.value,
    required this.expandedHeight,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("value=${value.abs()}");
    var width = MediaQuery.of(context).size.width;
    return Column(
      children: [
        Container(
          child: Image.network(
            'https://pic4.zhimg.com/80/v2-b02e601349241df0e3f25fd1ec622155_1440w.jpg',
            fit: BoxFit.cover,
            width: width,
            height: expandedHeight + value.abs(),
          ),
        ),
        Container(
          width: width - 28.w,
          height: 50.h,
          alignment: Alignment.center,
          color: KColors.c_F2E9FF,
          child: Text(SearchStrRes.find_your_drive,
              style: KTheme.normalTextStyle14),
        )
      ],
    );
  }
}
